<?php
declare (strict_types = 1);

namespace app\api\controller;

use app\BaseController;
use app\middleware\api\Auth;
use app\model\RecordIntegral;
use app\model\Users;
use app\model\UsersIntegral;
use app\model\Wallet;


class User extends BaseController
{
    protected $middleware=[Auth::class];

    /**
     * 用户详情
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {

        $user=Users::find(request()->userid);
        $integral=UsersIntegral::order('integral')->select(); //給用戶分配等級
        foreach ($integral as $v){
            if($user->integral>=$v->integral){
                $user->users_integral_id=$v->id;
                $user->save();

            }
        }
        $model= Users::with('grade')->find(request()->userid)->hidden(['password']);
        return $this->success($model);
    }

    /**
     * 修改用户资料
     * @return \think\response\Json
     */
    public function edit()
    {

        $params=\request()->param();
        if(!empty($params['password'])){
            $params['password']=password_hash($params['password'],PASSWORD_DEFAULT);
        }
        Users::where('id',request()->userid)->update($params);
        return $this->success();
    }


    /**
     * 注销用户
     * @return \think\response\Json
     */
    public function delete()
    {
        Users::where('id',request()->userid)->delete();
        return $this->success();
    }

    /**
     * 积分记录
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function record()
    {
      return $this->success(  RecordIntegral::where('users_id',request()->userid)->select());
    }

    public function wallet()
    {
        return $this->success(Wallet::where('users_id',request()->userid)->order('id','desc')->paginate(10));
    }
}
